import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // // start progress bar
  // NProgress.start()

  // // set page title
  // document.title = getPageTitle(to.meta.title)

  // // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    // 有token
    if (store.getters.userInfo) {
      // 并且可以拿得到数据
      next()
    } else {
      // token不一定正确
      try {
        await store.dispatch('user/getUserInfoAction')
        // console.log();
        if (to.path === '/login') {
          next({ path: '/' })
        } else {
          next()
        }
      } catch (error) {
        console.log(error)
        console.log('假token')
        removeToken()
        Message.warning('请重新登录')
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
